package com.neusoft.neuiotms.dcom.service.malfunction.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcom.constants.DCOMConstants;
import com.neusoft.neuiotms.dcom.converter.malfunction.MalfunctionFrontlineProcessingFormConverter;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionFrontlineProcessingFormDTO;
import com.neusoft.neuiotms.dcom.model.Institutions;
import com.neusoft.neuiotms.dcom.model.OperationGroup;
import com.neusoft.neuiotms.dcom.model.malfunction.MalfunctionApplyForm;
import com.neusoft.neuiotms.dcom.model.malfunction.MalfunctionFrontlineProcessingForm;
import com.neusoft.neuiotms.dcom.repository.InstitutionsRepository;
import com.neusoft.neuiotms.dcom.repository.OperationGroupRepository;
import com.neusoft.neuiotms.dcom.repository.malfunction.MalfunctionApplyFormRepository;
import com.neusoft.neuiotms.dcom.repository.malfunction.MalfunctionFrontlineProcessingFormRepository;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionFrontlineProcessingFormService;
import com.neusoft.neuiotms.micro.dcam.DcamMicroService;

@Service
public class MalfunctionFrontlineProcessingFormServiceImpl implements MalfunctionFrontlineProcessingFormService {

    @Autowired
    private MalfunctionFrontlineProcessingFormConverter malfunctionFrontlineProcessingFormConverter;
    @Autowired
    private MalfunctionFrontlineProcessingFormRepository malfunctionFrontlineProcessingFormRepository;
    @Autowired
    private InstitutionsRepository institutionsRepository;
    @Autowired
    private OperationGroupRepository operationGroupRepository;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private DcamMicroService dcamMicroService;
    @Autowired
    private MalfunctionApplyFormRepository malfunctionApplyFormRepository;

    @Override
    @Transactional
    public MalfunctionFrontlineProcessingFormDTO create(
            final MalfunctionFrontlineProcessingFormDTO dto,
            final UserBean user) {

        // 查询当前workNum和TaskId下是否存在记录
        final MalfunctionFrontlineProcessingForm oldModel =
                this.malfunctionFrontlineProcessingFormRepository.findByWorkNumAndTaskId(
                        dto.getWorkNum(), dto.getTaskId());

        //判断是否为暂存状态
        if (DCOMConstants.STR_TEMPORARY.equals(dto.getStatus())) {
            // 暂存工单
            dto.setWorkNum(dto.getWorkNum());
        } else {
            //设置一线运维人员解决情况
            this.processInstanceService.setGlobalVariable(dto.getTaskId(),
                    DCOMConstants.MALFUNCTION_PROCESS_FIRST_LINE_WHETHER_SOLVE, dto.getSolved());
            // 查找一线运维人员对应的组长
            final Institutions institutions =
                    this.institutionsRepository.findByResidents_UsernameIn(Arrays.asList(user.getUsername()));
            if (null != institutions) {
                final List<Institutions> institutionList = new ArrayList<>();
                institutionList.add(institutions);
                final OperationGroup operationGroup =
                        this.operationGroupRepository.findByInstitutionsIn(institutionList);
                if (null != operationGroup) {
                    // 流程中设置组长的编码
                    this.processInstanceService.setGlobalVariable(dto.getTaskId(),
                            DCOMConstants.MALFUNCTION_PROCESS_EXECUTOR_OPERATION_TEAMLEADER,
                            operationGroup.getGroupLeaderCode());
                }
            }

            // 完成节点
            this.processInstanceService.complete(dto.getWorkNum(), dto.getTaskId(), user);
        }

        // 如果不存在新增
        if (oldModel == null) {
            dto.setId(null);
        }

        final MalfunctionFrontlineProcessingForm model = this.malfunctionFrontlineProcessingFormConverter.toModel(dto);
        this.malfunctionFrontlineProcessingFormRepository.save(model);

        return this.malfunctionFrontlineProcessingFormConverter.toDTO(model);
    }

    @Override
    public MalfunctionFrontlineProcessingFormDTO detail(final String workNum, final String taskId,
            final UserBean user) {

        MalfunctionFrontlineProcessingForm model = null;
        try {
            if (StringUtils.isNotBlank(workNum) && !DCOMConstants.STR_NULL.equals(taskId)) {
                model = this.malfunctionFrontlineProcessingFormRepository.findByWorkNumAndTaskId(workNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String fromProcessTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (fromProcessTaskId == null) {
                        final MalfunctionFrontlineProcessingFormDTO dto = new MalfunctionFrontlineProcessingFormDTO();
                        // 设置参与工程师
                        final Object helperCode = this.processInstanceService.getVariables(workNum,
                                DCOMConstants.MALFUNCTION_PROCESS_HELPER_ENGINEER_CODE, null);
                        dto.setHelperEngineerCode(helperCode != null ? helperCode.toString() : "");
                        final Object helperName = this.processInstanceService.getVariables(workNum,
                                DCOMConstants.MALFUNCTION_PROCESS_HELPER_ENGINEER_NAME, null);
                        dto.setHelperEngineerName(helperName != null ? helperName.toString() : "");
                        // 关联的备品备件的详细信息
                        dto.setStocks(this.dcamMicroService
                                .searchFinishStockListByWorknumAndConfirmUser(workNum, user.getUsername()).getData());
                        return dto;
                    } else {
                        model = this.malfunctionFrontlineProcessingFormRepository.findByWorkNumAndTaskId(workNum,
                                fromProcessTaskId);

                        // 设置参与工程师
                        final Object helperCode = this.processInstanceService.getVariables(workNum,
                                DCOMConstants.MALFUNCTION_PROCESS_HELPER_ENGINEER_CODE, null);
                        model.setHelperEngineerCode(helperCode != null ? helperCode.toString() : "");
                        final Object helperName = this.processInstanceService.getVariables(workNum,
                                DCOMConstants.MALFUNCTION_PROCESS_HELPER_ENGINEER_NAME, null);
                        model.setHelperEngineerName(helperName != null ? helperName.toString() : "");
                    }
                }
            } else if (DCOMConstants.STR_NULL.equals(taskId)) {
                model = this.malfunctionFrontlineProcessingFormRepository.findTopByWorkNumOrderByIdDesc(workNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workNum },
                    new Object[] {taskId });
        }

        final MalfunctionFrontlineProcessingFormDTO dto = this.malfunctionFrontlineProcessingFormConverter.toDTO(model);
        // 关联的备品备件的详细信息
        final MalfunctionApplyForm malfunctionApplyForm =
                this.malfunctionApplyFormRepository.findTopByWorkNumOrderByIdDesc(workNum);
        dto.setStocks(this.dcamMicroService
                .searchFinishStockListByWorknumAndConfirmUser(workNum, malfunctionApplyForm.getFrontlineEngineerCode())
                .getData());
        return dto;
    }

}
